"""
    利用OpenCv实现图片二值化
"""
import cv2
import numpy as np
from tqdm import tqdm
# tqdm模块作用为生成进度条
# tqdm demo：
# from tqdm import tqdm
# from time import sleep
# for i in tqdm(range(1000)):
#     sleep(0.01)


# 灰度图
def Gray_img(img):
    # img_gray = cv.cvtColor(img_2, cv.COLOR_RGB2GRAY)
    print(img.shape)
    (h, w, c) = img.shape
    img_b = img[:, :, 0]
    img_g = img[:, :, 1]
    img_r = img[:, :, 2]
    img_gray = img_r * 0.299 + img_g * 0.587 + img_b * 0.114
    img_gray = img_gray.astype(np.uint8)  # (1)
    cv2.namedWindow("gray", 0)
    cv2.imshow('gray', img_gray)
    return img_gray


# 固定阈值二值化
# 较慢，利用tqdm模块加入进度条
def Binaryzation_img(img_gray):
    h = img_gray.shape[0]
    w = img_gray.shape[1]
    # 唯一确定阈值
    a = 120  # 二进制阀值
    img_bin = np.zeros((h, w), np.uint8)
    for i in tqdm(range(h)):
        for j in range(w):
            if img_gray[i, j] > a:
                img_bin[i, j] = 255
            else:
                img_bin[i, j] = 0
    cv2.namedWindow("bin", 0)
    cv2.imshow("bin", img_bin)
    return img_bin


# 图片锐化
def Sharpen_img(img_bin):
    kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32)  # 锐化
    img_sharpen = cv2.filter2D(img_bin, -1, kernel=kernel)
    cv2.namedWindow("sharpen", 0)
    cv2.imshow("sharpen", img_sharpen)
    return img_sharpen


src = "JPG/1.jpg"  #"TIF/thermal/classified.jpg"
img = cv2.imread(src)
cv2.namedWindow("input image", 0)
cv2.imshow("input image", img)
img_gray = Gray_img(img)
img_bin = Binaryzation_img(img_gray)
img_sharpen = Sharpen_img(img_bin)
cv2.waitKey(0)
